package org.jivesoftware.smackx.snyc.provider;

import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smackx.snyc.packet.RosterItem;
import org.jivesoftware.smackx.snyc.packet.RosterSubscribeElement;
import org.jivesoftware.smackx.snyc.packet.RosterUnsubscribeElement;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class RosterUnsubscribeExtProvider extends ExtensionElementProvider<RosterUnsubscribeElement> {

	@Override
	public RosterUnsubscribeElement parse(XmlPullParser parser, int initialDepth) throws Exception {
        RosterUnsubscribeElement rosterUnsubscribe = new RosterUnsubscribeElement();
//        String name =  parser.getAttributeValue("", "name");
        String type =  parser.getAttributeValue("", "type");

//        rosterUnsubscribe.setName(name);
        rosterUnsubscribe.setType(type);

        outerloop: while (true) {
            int eventType = parser.next();
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    String startTag = parser.getName();
                    switch (startTag) {
                        case "item":
                            RosterItem item = parseItem(parser);
                            rosterUnsubscribe.setItem(item);
                            break;
                    }
                    break;
                case XmlPullParser.END_TAG:
                    String endTag = parser.getName();
                    switch (endTag) {
                        case "unsubscribe":
                            if (parser.getDepth() == initialDepth) {
                                break outerloop;
                            }
                    }
            }
        }
		
		return rosterUnsubscribe;
	}

    public static RosterItem parseItem(XmlPullParser parser) throws XmlPullParserException, IOException {
        String jidString = parser.getAttributeValue("", "jid");
        String itemName = parser.getAttributeValue("", "name");
        String subscription = parser.getAttributeValue("", "subscription");

        // Create item.
        RosterItem item = new RosterItem();
        item.setJid(jidString);
        item.setName(itemName);
        item.setSubscription(subscription);

        return item;
    }

}
